<?php

namespace app\controller\gas;

use app\BaseController;
use app\model\StationBasic;
use think\facade\Cache;
use think\Response;

class Auth extends BaseController
{
    public function login(): Response
    {
        $param = $this->request->post();
        $account = $this->app->make(StationBasic::class)->where('account', $param['username'])->where('state', 1)->find();
        if (empty($account)) throw new \Exception("油站不存在");
        if (!checkPassword($param['password'], $account['token'], $account['password'])) throw new \Exception("密码错误");
        $token = setCacheToken("gas");
        Cache::set("gas_" . $token, [
            "id" => $account['id'],
            "account" => $account['account'],
            "token" => $token
        ], 24 * 60 * 60);
        return $this->success(['id' => $account['id'], 'token' => $token]);
    }

    public function check(): Response
    {
        return $this->success($this->request->station);
    }

    public function modify(): Response
    {
        $admin = $this->request->station;
        $data = $this->request->post();
        if (!checkPassword($data['oldPassword'], $admin['token'], $admin['password'])) throw new \Exception("原密码错误");
        $password = setPassword($data['newPassword']);
        $admin['password'] = $password['password'];
        $admin['token'] = $password['token'];
        $admin->save();
        return $this->success();
    }
}
